package com.base.delegate

import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * anthor:zhouzechao
 * data: 2019-11-14
 * desc: 观察内容变化
 */
fun <T : Any> observer(
    initialValue: T, onChange: (oldValue: T, newValue: T) -> Unit
): Observer<T> = Observer(initialValue).setOnChange(onChange)

class Observer<T>(initialValue: T) : ReadWriteProperty<Any?, T> {
    private var onChange by weak<(T, T) -> Unit>()
    private var value = initialValue

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        return value
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        val oldValue = this.value
        if (oldValue != value) {
            onChange?.invoke(oldValue, value)
        }
        this.value = value
    }

    fun setOnChange(onChange: (T, T) -> Unit): Observer<T> {
        this.onChange = onChange
        return this
    }
}